package com.example.experiment04;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    Button bind,unbind,getServicesStatus;
    BindService.MyBinder binder;


    private ServiceConnection conn=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {

           // Log.d("GsonUtils","onServiceConnected");
            //binder=(BindService.MyBinder)iBinder;

            System.out.println("--Service Connected--");

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            //Log.d("GsonUtils","onServiceDisconnected");

            System.out.println("--Service Disconnected--");

        }
    };

   // Intent intent;
    //private TextView textView;
    //private TextView count;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 获取程序界面中的start、stop、getServiceStatus按钮
        bind = (Button) findViewById(R.id.bind);
        unbind = (Button) findViewById(R.id.unbind);
        getServicesStatus= (Button) findViewById(R.id.getServiceStatus);
        //创建启动Service的Intent
        final Intent intent = new Intent();
        //为Intent设置Action属性

        intent.setAction("com.example.experiment04.service.Bind_SERVICE");
        intent.setPackage("com.example.experiment04");


        bind.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View source){
                //绑定指定Serivce
                bindService(intent,conn,Service.BIND_AUTO_CREATE);


            }
        });

        unbind.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View source){
                //解除绑定Serivce
                unbindService(conn);

            }
        });
        getServicesStatus.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View source){
                // 获取、并显示Service的count值
                Toast.makeText(MainActivity.this
                        , "Serivce的count值为：" + binder.getCount()
                        , 4000).show();
            }
        });



    }
}
